import request from '../utils/request';
import { type ManufacturerItem, type ManufacturerParams, type ManufacturerWithSchools } from '../types/manufacturer';
import { type ApiResponse } from '../types/auth';
import { stringify } from 'querystring';
/**
 * 获取厂商列表
 * @param params 查询参数
 * @returns 厂商列表
 */
export const getManufacturerList = (params?: ManufacturerParams): Promise<{ manufacturers: ManufacturerItem[] }> => {
    return request.get('/manufacturer/list', { params });
};

/**
 * 获取厂商列表
 * @param params 查询参数
 * @returns 厂商列表
 */
export const getManufacturerWithSchools = (params?: ManufacturerParams): Promise<{ manufacturers: ManufacturerWithSchools[] }> => {
    return request.get('/manufacturer/listWithSchools', { params });
};

/**
 * 查询厂商列表
 * @param params 查询参数
 * @returns 厂商列表
 */
export const searchManufacturerWithSchools = (params: { name?: string, status?: number }): Promise<{ manufacturers: ManufacturerWithSchools[] }> => {
    const validParams = Object.entries(params).reduce((acc, [key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
            acc[key] = value;
        }
        return acc;
    }, {} as Record<string, string | number>);

    // 拼接查询字符串（如果有参数）
    const queryString = Object.keys(validParams).length > 0
        ? `?${stringify(validParams)}`
        : '';

    // 发送带参数的GET请求
    return request.get(`/manufacturer/search${queryString}`);
};

/**
 * 获取厂商详情带学校信息
 * @param id 厂商ID
 * @returns 厂商详情
 */
export const getManufacturerDetail = (id: number) => {
    return request.get<ApiResponse<ManufacturerItem>>(`/manufacturer/${id}`);
};

/**
 * 创建厂商
 * @param data 厂商信息
 * @returns 操作结果
 */
export const createdManufacturer = (data: Omit<ManufacturerItem, 'id' | 'createdAt' | 'updatedAt'>) => {
    return request.post<ApiResponse<{ id: number }>>('/manufacturer/create', data);
};

/**
 * 更新厂商
 * @param id 厂商ID
 * @param data 厂商信息
 * @returns 操作结果
 */
export const updateManufacturer = (data: Omit<ManufacturerItem, 'createdAt' | 'updatedAt'>) => {
    return request.put<ApiResponse<{ success: boolean }>>(`/manufacturer/${data.id}`, data);
};


/**
 * 删除厂商
 * @param id 厂商ID
 * @returns 操作结果
 */
export const deleteManufacturer = (id: number) => {
    return request.delete<ApiResponse<{ success: boolean }>>(`/manufacturer/${id}`);
};